import React, { forwardRef, useEffect, useImperativeHandle, useState, useMemo, useRef } from 'react'
import { Button, Form, Space, Table, Pagination } from 'antd'
const styles = {
  display: 'flex',
  flexDirection: 'row',
  justifyContent: 'flex-end',
  alignItems: 'center'
}

const MyListPage = forwardRef(({ formConfig, tableConfig }, ref) => {
  const [form] = Form.useForm()
  const [initialValues, setInitialValues] = useState(undefined)
  const [dataSource, setDataSource] = useState([])
  const tableInstance = useRef(null)
  useImperativeHandle(ref, () => {
    return {
      form: {
        ...form,
        forceUpdate,
        reset,
      },
      table: {
        nativeElement: tableInstance.current.nativeElement,
        scrollTo: tableInstance.current.scrollTo,
        setDataSource,
      }
    }
  })
  useEffect(() => {
    if (typeof formConfig.initValues === 'string') {
      window.$api[formConfig.initValues]().then(res => {
        setInitialValues(() => res)
      })
    }
    if (Object.prototype.toString.call(formConfig.initValues) ==='[object Object]') {
      setInitialValues(() => formConfig.initValues)
    }
  }, [])
  useEffect(() => {
    if (initialValues) {
      reset()
    }
  }, [initialValues])
  const [formVersion, setFormVersion] = useState(0) // 用于监听formData变化，更新disable或者其它
  const forceUpdate = () => {
    setFormVersion(v => v + 1)
  }
  const reset = () => {
    Object.keys(form.getFieldsValue()).forEach(key => {
      if (initialValues && initialValues[key]) {
        form.setFieldValue(key, initialValues[key])
      } else {
        form.setFieldValue(key, undefined)
      }
    })
    forceUpdate()
    // 重置完成后，调查询接口
    console.log(window.$api)
    window.$api.submit(form.getFieldsValue()).finally(() => {
      setDataSource([
        { name: 'ygy1', age: 18 },
        { name: 'ygy2', age: 19 },
        { name: 'ygy3', age: 20 },
        { name: 'ygy4', age: 21 },
        { name: 'ygy5', age: 21 },
        { name: 'ygy6', age: 21 },
        { name: 'ygy7', age: 21 },
        { name: 'ygy8', age: 21 },
        { name: 'ygy9', age: 21 },
        { name: 'ygy10', age: 21 },
        { name: 'ygy11', age: 21 },
        { name: 'ygy12', age: 21 },
        { name: 'ygy13', age: 21 },
        { name: 'ygy14', age: 21 }
      ])
    })
  }
  const onValuesChange = (changedValues, allValues) => {
    forceUpdate()
  }

  // 优化渲染性能
  const FormItems = useMemo(() => {
    return (formConfig.list ?? []).map(({ bind, Component, ...restItem }) => {
      // 常用的两个可以联动的属性抽出来做动态
      const disabled = typeof bind.disabled === 'function' ? bind.disabled(form) : bind.disabled
      const allowClear = typeof bind.allowClear === 'function' ? bind.allowClear(form) : bind.allowClear
      return (
        <Form.Item style={{ marginBottom: '8px' }} {...restItem} key={restItem.name}>
          <Component
            name={restItem.name}
            parent={form}
            style={{ width: '100%' }}
            {...bind}
            disabled={disabled}
            allowClear={allowClear}
          />
        </Form.Item>
      )
    })
  }, [formVersion])
  return (
    <>
      <Form
        className="form-component"
        layout="inline"
        autoComplete="off"
        labelWrap
        initialValues={initialValues}
        form={form}
        size="small"
        onValuesChange={onValuesChange}
        { ...formConfig.config }>
        { FormItems }
        <Form.Item colon={false} label={" "}>
          <Space>
            {
              (formConfig.buttons ?? []).map((attrs) => {
                return (
                  <Button
                    size="small"
                    {...attrs}
                    key={attrs.key}
                  >
                    {attrs.text}
                  </Button>
                )
              })
            }
          </Space>
        </Form.Item>
      </Form>
      {
        (tableConfig.buttons ?? []).map((attrs) => {
          return (
            <Button
              size="small"
              {...attrs}
              key={attrs.key}
            >
              {attrs.text}
            </Button>
          )
        })
      }
      <div style={{ marginBottom: '10px' }} />
      <Table ref={tableInstance} pagination={false} columns={tableConfig.columns} dataSource={dataSource} />
      <div style={styles}>
        <Pagination />
      </div>
    </>
  )
})

export default MyListPage
